package com.tlgen.modules.system.service.impl;

import com.tlgen.common.exception.EntityExistException;
import com.tlgen.common.utils.FileUtil;
import com.tlgen.common.utils.PageUtil;
import com.tlgen.common.utils.QueryHelp;
import com.tlgen.common.utils.ValidationUtil;
import com.tlgen.modules.system.domain.CSort;
import com.tlgen.modules.system.repository.SortRepository;
import com.tlgen.modules.system.service.SortService;
import com.tlgen.modules.system.service.dto.SortDto;
import com.tlgen.modules.system.service.dto.SortQueryCriteria;
import com.tlgen.modules.system.service.mapper.SortMapper;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@Service
@CacheConfig(cacheNames = "sort")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class SortServiceImpl implements SortService {

    private final SortRepository sortRepository;

    private final SortMapper sortMapper;

    public SortServiceImpl(SortRepository sortRepository, SortMapper sortMapper) {
        this.sortRepository = sortRepository;
        this.sortMapper = sortMapper;
    }


    /**
     * 不带条件分页查询
     * @param pageable 分页参数
     * @return
     */
    @Override
    @Cacheable
    public Object queryAll(Pageable pageable) {
        return sortMapper.toDto(sortRepository.findAll(pageable).getContent());
    }


    /**
     * 带条件分页查询
     * @param criteria 条件
     * @param pageable 分页参数
     * @return
     */
    @Override
    @Cacheable
    public Object queryAll(SortQueryCriteria criteria, Pageable pageable) {
        Page<CSort> page = sortRepository.findAll((root, criteriaQuery, criteriaBuilder) ->
                QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(sortMapper::toDto));
    }

    /**
     * 带条件不分页查询
     * @param criteria 条件
     * @return
     */
    @Override
    @Cacheable
    public List<SortDto> queryAll(SortQueryCriteria criteria) {
        return sortMapper.toDto(sortRepository.findAll((root, criteriaQuery, criteriaBuilder) ->
                QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    /**
     * 新增
     * @param resources /
     * @return
     */
    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public SortDto create(CSort resources) {
        if(sortRepository.findByName(resources.getName()) != null){
            throw new EntityExistException(CSort.class,"name",resources.getName());
        }
        return sortMapper.toDto(sortRepository.save(resources));
    }

    /**
     * 编辑
     * @param resources /
     */
    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void update(CSort resources) {
        CSort CSort = sortRepository.findById(resources.getId()).orElseGet(CSort::new);
        ValidationUtil.isNull(CSort.getId(),"sort","id",resources.getId());

       CSort CSort1 = sortRepository.findByName(resources.getName());

        if(CSort1 != null && !CSort1.getId().equals(CSort.getId())){
            throw new EntityExistException(CSort.class,"sort",resources.getName());
        }

        CSort.setCode(resources.getCode());
        CSort.setName(resources.getName());
        sortRepository.save(CSort);
    }

    /**
     * 根据Id查询
     * @param id /
     * @return
     */
    @Override
    @Cacheable(key = "#p0")
    public SortDto findById(long id) {
        CSort CSort = sortRepository.findById(id).orElseGet(CSort::new);
        ValidationUtil.isNull(CSort.getId(),"sort","id",id);
        return sortMapper.toDto(CSort);
    }

    /**
     * 删除
     * @param ids /
     */
    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void delete(Set<Long> ids) {
        for (Long id : ids) {
            sortRepository.deleteById(id);
        }
    }

    /**
     * 导出数据
     * @param response /
     * @throws IOException
     */
    @Override
    public void download(List<SortDto> sortDtos, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (SortDto sortDto : sortDtos) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("慢性病编号", sortDto.getCode());
            map.put("慢性病名称", sortDto.getName());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

}
